package com.github.cyf.async.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author chenyifan
 * @create 2024-03-17 18:07
 */
@Configuration
@EnableAsync // 使用异步方法时需要提前开启(在启动类上或配置类上)
public class AsyncConfig implements AsyncConfigurer {

    private static final int corePoolSize = 5;
    private static final int maxPoolSize = 20;
    private static final int keepAliveTime = 100;
    private static final int queueCapacity = 200;
    private static final String threadNamePrefix = "async-exec-";

    /**
     * 自定义线程池
     * @return
     */
    @Override
    @Bean("threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        // 最大可创建的线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 等待队列最大长度
        executor.setQueueCapacity(queueCapacity);
        // 线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(keepAliveTime);
        // 线程池对拒绝任务(无线程可用)的处理策略
        // 当线程池和队列已满，新提交的任务将由调用者所在的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程名前缀
        executor.setThreadNamePrefix(threadNamePrefix);

        // 线程池对任务的包装，用于解决父子线程间的数据复用
        executor.setTaskDecorator(new ContextTaskDecorator());
        return executor;
    }

    /**
     * 自定义异常处理
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }
}